package com.example.giftrecord.controller;

import com.example.giftrecord.entity.GiftRecord;
import com.example.giftrecord.service.IGiftRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;

/**
 * <p>
 * 礼金记录表 前端控制器
 * </p>
 *
 * @author example
 * @since 2023-07-15
 */
@RestController
@RequestMapping("/gift-records")
@CrossOrigin(origins = "*") // 允许跨域访问，实际生产环境应限制来源
public class GiftRecordController {

    @Autowired
    private IGiftRecordService giftRecordService;

    /**
     * 获取所有礼金记录
     * @return 礼金记录列表
     */
    @GetMapping
    public ResponseEntity<List<GiftRecord>> getAllRecords() {
        List<GiftRecord> records = giftRecordService.getAllRecords();
        return ResponseEntity.ok(records);
    }

    /**
     * 根据ID获取礼金记录
     * @param id 记录ID
     * @return 礼金记录
     */
    @GetMapping("/{id}")
    public ResponseEntity<GiftRecord> getRecordById(@PathVariable Long id) {
        GiftRecord record = giftRecordService.getRecordById(id);
        if (record == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(record);
    }

    /**
     * 添加礼金记录
     * @param giftRecord 礼金记录
     * @return 添加的礼金记录
     */
    @PostMapping
    public ResponseEntity<GiftRecord> addRecord(@RequestBody GiftRecord giftRecord) {
        boolean success = giftRecordService.addRecord(giftRecord);
        if (success) {
            return ResponseEntity.ok(giftRecord);
        }
        return ResponseEntity.badRequest().build();
    }

    /**
     * 更新礼金记录
     * @param id 记录ID
     * @param giftRecord 礼金记录
     * @return 更新后的礼金记录
     */
    @PutMapping("/{id}")
    public ResponseEntity<GiftRecord> updateRecord(@PathVariable Long id, @RequestBody GiftRecord giftRecord) {
        // 确保ID一致
        giftRecord.setId(id);
        
        boolean success = giftRecordService.updateRecord(giftRecord);
        if (success) {
            return ResponseEntity.ok(giftRecord);
        }
        return ResponseEntity.notFound().build();
    }

    /**
     * 删除礼金记录
     * @param id 记录ID
     * @return 响应结果
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteRecord(@PathVariable Long id) {
        boolean success = giftRecordService.deleteRecord(id);
        if (success) {
            return ResponseEntity.noContent().build();
        }
        return ResponseEntity.notFound().build();
    }
}
    